package com.ruoyi.combat.util.weibo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.useralignment.CombatRelationWb;
import com.ruoyi.combat.domain.userlocation.CombatRelation;
import com.ruoyi.combat.mapper.useralignment.CombatRelationWbMapper;
import com.ruoyi.combat.mapper.useralignment.CombatUserWbMapper;
import com.ruoyi.combat.mapper.userlocation.CombatRelationMapper;
import com.ruoyi.combat.util.weibo.entity.*;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Component
public class WeiboApiUtil {

    //    private  String url = "http://192.168.124.114";
    @Value("${weibo.crawlIp}")
    private String url;
    @Autowired
    private WeiboUtil weiboUtil;
    @Autowired
    private CombatRelationMapper combatRelationMapper;
    @Autowired
    private CombatRelationWbMapper combatRelationWbMapper;

    public String uploadImg(String cookie, byte[] img, String type) {
        String result = "";
        String urlPath = url + ":5066/uploadImgWB";
        try {
            Map data = new HashMap();
            data.put("cookie", cookie);
            data.put("image_data", Base64.getEncoder().encodeToString(img));
            data.put("file_type", type);
            String jsonStr = JSONUtil.toJsonStr(data);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 发微博
     *
     * @param cookie
     * @param content
     * @param img
     * @param ip
     * @return
     */
    public String sendContent(String cookie, String content, String img, String ip) {
        String result = "";
        String urlPath = url + ":5089/sendMsg";
        try {
            Map data = new HashMap();
            data.put("cookie", cookie);
            data.put("content", content);
            if (StringUtils.isNotEmpty(img)) {
                data.put("pic_id", img);
            }
            String jsonStr = JSONUtil.toJsonStr(data);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 关注
     * @param userId
     * @param list
     * @return
     */
    public String tofollow(String userId, List<String> list) {
        String result = "";
       /* String urlPath = url + ":5001/tofollow";
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("target_ids", list);
            data.put("cookie", cookie);
            String jsonStr = JSONUtil.toJsonStr(data);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }*/
        weiboUtil.follow(userId, list);
        return result;
    }

    /**
     * 删除
     * @param cookie
     * @param list
     * @return
     */
    public String todestroy(String cookie, List<String> list) {
        String result = "";
        /*String urlPath = url + ":5018/destroy";
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("target_ids", list);
            data.put("cookie", cookie);
            String jsonStr = JSONUtil.toJsonStr(data);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }*/
        weiboUtil.deleteweibo(cookie, list.get(0));
        return result;
    }

    /**
     * 取消关注
     * @param userId
     * @param list
     * @return
     */
    public String unfollow(String userId, List<String> list) {
        String result = "";
        /*String urlPath = url + ":5002/unfollow";
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("target_ids", list);
            data.put("cookie", cookie);
            String jsonStr = JSONUtil.toJsonStr(data);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }*/
        weiboUtil.unfollow(userId, list);
        return result;
    }

    public String getFriends(List<Map<String, String>> list) {
//        String urlPath = "http://192.168.124.223:5222/crawl";
        String urlPath = url + ":5222/crawl1";
        String result = "";
       /* try {
            Map amp = new HashMap();
            amp.put("tasks", list);
            String jsonStr = JSONUtil.toJsonStr(amp);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        {
    "code": 200,
    "msg": "批量获取完成，共处理 1 个博主",
    "data": {
        "results": {
            "6972663192": {
                "total": 17,
                "follows": [
                    {
                        "id": "7895820249",
                        "name": "空手不空谈"
                    },
                    {
                        "id": "1877951477",
                        "name": "周若雪Patty"
                    },
        */

        for (Map<String, String> map : list) {
            String uid = map.get("user_id");
            String follows = weiboUtil.get_follows(uid);
            if (StringUtils.isNotEmpty(follows)) {
                WeiboFollowResponse bean = JSONUtil.toBean(follows, WeiboFollowResponse.class);
                FollowData data = bean.getData();
                Map<String, FollowResult> results = data.getResults();
                FollowResult followResult = results.get(uid);
                List<Follow> follows1 = followResult.getFollows();
                List<String> ids = new ArrayList<>();
                follows1.forEach(follow -> {
                    ids.add(follow.getId());
                });
                ids.add(uid);
                String usersInfo = weiboUtil.getUsersInfo(uid, ids);
                Map<String,String> address = new HashMap();
                if (StringUtils.isNotEmpty(usersInfo)) {
                    UserInfoResponse bean1 = JSONUtil.toBean(usersInfo, UserInfoResponse.class);
                    UserInfoData data1 = bean1.getData();
                    List<UserInfoResult> results1 = data1.getResults();
                    results1.forEach(userInfoResult -> {
                        UserInfo userInfo = userInfoResult.getUser_info();
                        address.put(userInfoResult.getTarget_id(),userInfo.getIpLocation());
                    });
                }
                follows1.forEach(follow -> {
                    CombatRelation combatRelation = new CombatRelation();
                    combatRelation.setUserid(uid);
                    combatRelation.setTargetid(follow.getId());
                    combatRelation.setRelation("关注");
                    combatRelation.setTargetName(follow.getName());
                    combatRelation.setPlate("微博");
                    combatRelation.setTargetCity(address.get(follow.getId()));
                    combatRelation.setUserCity(address.get(uid));
                    combatRelation.setStatus("0");
                    combatRelationMapper.insertCombatRelation(combatRelation);

                    CombatRelationWb combatRelationWb = new CombatRelationWb();
                    combatRelationWb.setUserid(uid);
                    combatRelationWb.setTargetid(follow.getId());
                    combatRelationWb.setRelation("关注");
                    combatRelationWb.setTargetName(follow.getName());
                    combatRelationWb.setPlate("微博");
                    combatRelationWb.setTargetCity(address.get(follow.getId()));
                    combatRelationWb.setUserCity(address.get(uid));
                    combatRelationWb.setStatus("0");
                    combatRelationWbMapper.insertCombatRelationWb(combatRelationWb);


                });


            }


//            combatRelationMapper
//            combatRelationWbMapper

        }

        return result;
    }

    public String getLatestWeibo(List<String> userIds) {
        String urlPath = url + ":5009/refresh";
        String result = "";
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("user_id_list", userIds);
            String jsonStr = JSONUtil.toJsonStr(data);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public String getLatestWeiboOneDay(List<String> userIds) {
        String urlPath = url + ":6001/refresh";
        String result = "";
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("user_id_list", userIds);
            String jsonStr = JSONUtil.toJsonStr(data);
            result = HttpUtil.post(urlPath, jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


}
